/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;

using Gtk;
using Mono.Unix;

#if ENABLE_DBUS
using NDesk.DBus;
using org.freedesktop.DBus;
#endif

using DCSharp;

namespace DCSharp.Gui
{
#if ENABLE_DBUS
	[Interface ("org.gnome.DCSharp")]
	public interface IApplication
	{
		void Present();
		void ConnectTo(string uri);
		void Shutdown();
	}

	public class Controller : IApplication
	{
		private const string ServiceName = "org.gnome.DCSharp";
		private static ObjectPath Path = new ObjectPath("/org/gnome/DCSharp");

		public static IApplication FindInstance()
		{
			if (Bus.Session.NameHasOwner(ServiceName))
			{
				return Bus.Session.GetObject<IApplication>(ServiceName, Path);
			}
			return null;
		}

		public void RegisterService()
		{
			Bus.Session.RequestName(ServiceName);
			Bus.Session.Register(ServiceName, Path, this);
		}

		public void UnregisterService()
		{
			Bus.Session.ReleaseName(ServiceName);
		}
#else
	public class Controller
	{
#endif
		public void HandleArgs(string[] args)
		{
			foreach (string arg in args)
			{
				ConnectTo(arg);
			}
		}

		public void Present()
		{
			Gui gui = Globals.Gui;
			if (gui != null)
			{
				MainWindow window = Globals.Gui.MainWindow;
				if (window != null)
				{
					window.Show();
				}
			}
		}

		public void ConnectTo(string uriString)
		{
			Uri uri;
			if (StringUtil.TryCreateUri(uriString, out uri))
			{
				Globals.Runtime.HubManager.ConnectTo(uri);
			}
			else
			{
				MessageDialog dialog = new MessageDialog(
					String.Format(Catalog.GetString("The address \"{0}\" could not be handled"), uriString),
					null, null, MessageType.Error, Globals.Gui.MainWindow);

				dialog.AddButton(Stock.Ok, ResponseType.Ok);

				dialog.Run();
				dialog.Destroy();
			}
		}

		public void Shutdown()
		{
			Gtk.Application.Quit();
		}
	}
}
